package com.justgame.project.cloud.common.util;

import com.alibaba.fastjson.JSONObject;
import com.justgame.project.cloud.common.exception.Exc;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * HTTP解析工具
 */
@Slf4j
@Component
public class HttpContextUtil {

    public static String BaiduLocationApi;

    public static HttpServletRequest getHttpRequest() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (NullPointerException nullPointerException) {
            throw new Exc("无法解析HTTP请求！");
        }
    }

    public static HttpServletResponse getHttpResponse() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        } catch (NullPointerException nullPointerException) {
            throw new Exc("无法获取Response！");
        }
    }

    public static String getBodyString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static HttpSession getSession() {
        return getHttpRequest().getSession();
    }

    public static String getDomain() {
        HttpServletRequest request = getHttpRequest();
        //   例如：http://localhost:8080/abc123/
        StringBuffer url = request.getRequestURL();
        //   获得如上"例如"的 http://localhost:8080
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getHttpRequest();
        return request.getHeader("Origin");
    }

    public static String getIp() {
        return getIp(getHttpRequest());
    }

    public static String getIp(HttpServletRequest request) {
        String ip = null;
        ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        //使用代理，则获取第一个IP地址
        if (StringUtils.isNotBlank(ip) && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
                log.info("IP:{},为反向代理请求。", ip);
            }
        }
        return ip;
    }

    public static String getRealAddr(HttpServletRequest request) {
        if (StringUtils.isBlank(BaiduLocationApi)) {
            return "";
        }
        try {
            String ip = getIp(request);
            if ("127.0.0.1".equals(ip)) {
                return "本地主机";
            }
            URL url = new URL(String.format(BaiduLocationApi, ip));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.connect();
            int code = connection.getResponseCode();
            if (!(code == 200)) {
                return "";
            }
            StringBuilder msg = new StringBuilder();
            // 正常响应
            // 从流中读取响应信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line = null;
            while ((line = reader.readLine()) != null) { // 循环从流中读取
                msg.append(line);
            }
            reader.close(); // 关闭流
            connection.disconnect();
            Map result = JSONObject.parseObject(msg.toString(), Map.class);
            try {
                return String.valueOf(((Map) result.get("content")).get("address"));
            } catch (NullPointerException e) {
                log.info(e.getMessage());
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getRealAddr() {
        return getRealAddr(getHttpRequest());
    }

    @Value("${BaiduAPI.getLocation:https://api.map.baidu.com/location/ip?ak=E7xXjxkO8KztQPadYGsyVFyuGXRqCXr4&ip=%s}")
    private void setBaiduApi(String val) {
        HttpContextUtil.BaiduLocationApi = val;
    }
}
